<template>
  <!-- 悬浮聊天图标 -->
  <div
    v-if="!isMinimized"
    class="ai-floating-icon"
    :style="iconStyle"
    @mousedown="startDrag"
    @click="toggleChat"
  >
    <div class="icon-wrapper">
      <el-icon :size="28" class="ai-icon">
        <ChatDotRound />
      </el-icon>
      <span v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</span>
    </div>
    <div class="icon-tooltip">AI助手</div>
  </div>

  <!-- 聊天窗口 -->
  <transition name="chat-slide">
    <div
      v-if="showChat"
      class="ai-chat-window"
      :style="chatWindowStyle"
      @mousedown.stop
    >
      <!-- 窗口头部 -->
      <div class="chat-header" @mousedown="startDragWindow">
        <div class="header-left">
          <el-icon :size="20" color="#fff"><Service /></el-icon>
          <span class="header-title">AI智能助手</span>
        </div>
        <div class="header-actions">
          <el-button
            text
            size="small"
            @click="minimizeChat"
            class="header-btn"
          >
            <el-icon color="#fff"><Minus /></el-icon>
          </el-button>
          <el-button
            text
            size="small"
            @click="closeChat"
            class="header-btn"
          >
            <el-icon color="#fff"><Close /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-messages" ref="messagesContainer">
        <div v-if="messages.length === 0" class="welcome-message">
          <el-icon :size="48" color="#409EFF"><Service /></el-icon>
          <p>你好！我是AI助手</p>
          <p>有什么可以帮你的吗？</p>
        </div>

        <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message-item', message.role]"
        >
          <div class="message-avatar">
            <el-avatar v-if="message.role === 'user'" :size="32">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="32" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon><Service /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>

        <!-- 加载中 -->
        <div v-if="isLoading" class="message-item assistant">
          <div class="message-avatar">
            <el-avatar :size="32" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon><Service /></el-icon>
            </el-avatar>
          </div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          placeholder="输入消息..."
          @keydown.enter.exact="handleSend"
          :disabled="isLoading"
        >
          <template #suffix>
            <el-button
              text
              :loading="isLoading"
              :disabled="!inputMessage.trim()"
              @click="handleSend"
            >
              <el-icon :size="20" color="#409EFF"><Promotion /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import {
  ChatDotRound,
  Service,
  User,
  Close,
  Minus,
  Promotion
} from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();

// 图标位置
const iconPosition = ref({
  x: window.innerWidth - 80,
  y: window.innerHeight - 80
});

// 聊天窗口位置
const chatWindowPosition = ref({
  x: window.innerWidth - 380,
  y: window.innerHeight - 550
});

// 拖拽状态
const isDragging = ref(false);
const isDraggingWindow = ref(false);
const dragOffset = ref({ x: 0, y: 0 });

// 显示状态
const showChat = ref(false);
const isMinimized = ref(false);

// 消息相关
const messages = ref([]);
const inputMessage = ref('');
const isLoading = ref(false);
const unreadCount = ref(0);

// 消息容器引用
const messagesContainer = ref(null);

// 计算图标样式
const iconStyle = computed(() => ({
  left: `${iconPosition.value.x}px`,
  top: `${iconPosition.value.y}px`
}));

// 计算聊天窗口样式
const chatWindowStyle = computed(() => ({
  left: `${chatWindowPosition.value.x}px`,
  top: `${chatWindowPosition.value.y}px`
}));

// 开始拖拽图标
const startDrag = (e) => {
  if (e.button !== 0) return; // 只响应左键
  
  isDragging.value = true;
  dragOffset.value = {
    x: e.clientX - iconPosition.value.x,
    y: e.clientY - iconPosition.value.y
  };
  
  e.preventDefault();
};

// 开始拖拽窗口
const startDragWindow = (e) => {
  if (e.button !== 0) return;
  
  isDraggingWindow.value = true;
  dragOffset.value = {
    x: e.clientX - chatWindowPosition.value.x,
    y: e.clientY - chatWindowPosition.value.y
  };
  
  e.preventDefault();
};

// 拖拽移动
const handleDrag = (e) => {
  if (isDragging.value) {
    const newX = e.clientX - dragOffset.value.x;
    const newY = e.clientY - dragOffset.value.y;
    
    // 限制在窗口范围内
    iconPosition.value = {
      x: Math.max(0, Math.min(newX, window.innerWidth - 60)),
      y: Math.max(0, Math.min(newY, window.innerHeight - 60))
    };
  }
  
  if (isDraggingWindow.value) {
    const newX = e.clientX - dragOffset.value.x;
    const newY = e.clientY - dragOffset.value.y;
    
    chatWindowPosition.value = {
      x: Math.max(0, Math.min(newX, window.innerWidth - 360)),
      y: Math.max(0, Math.min(newY, window.innerHeight - 500))
    };
  }
};

// 结束拖拽
const endDrag = () => {
  isDragging.value = false;
  isDraggingWindow.value = false;
};

// 切换聊天窗口
const toggleChat = (e) => {
  // 如果正在拖拽，不触发打开
  if (isDragging.value) {
    isDragging.value = false;
    return;
  }
  
  showChat.value = !showChat.value;
  isMinimized.value = false;
  
  if (showChat.value) {
    unreadCount.value = 0;
    scrollToBottom();
  }
};

// 最小化聊天
const minimizeChat = () => {
  showChat.value = false;
  isMinimized.value = false;
};

// 关闭聊天
const closeChat = () => {
  showChat.value = false;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 格式化时间
const formatTime = () => {
  const now = new Date();
  return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
};

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || isLoading.value) {
    return;
  }

  const userMessage = inputMessage.value.trim();
  inputMessage.value = '';

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userMessage,
    time: formatTime()
  });

  scrollToBottom();
  isLoading.value = true;

  try {
    // 构建历史消息
    const history = messages.value.map(msg => ({
      role: msg.role,
      content: msg.content
    }));

    // 调用后端流式API
    const response = await fetch(proxy.http.ipAddress + 'api/AIChat/stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        message: userMessage,
        history: history.slice(0, -1) // 排除刚添加的用户消息
      })
    });

    if (!response.ok) {
      throw new Error('请求失败');
    }

    // 读取流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    // 创建AI消息
    const aiMessage = {
      role: 'assistant',
      content: '',
      time: formatTime()
    };
    messages.value.push(aiMessage);

    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      
      if (done) {
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      
      // 处理每一行数据
      const lines = buffer.split('\n');
      buffer = lines.pop(); // 保留最后一个不完整的行

      for (const line of lines) {
        if (line.startsWith('data:')) {
          const dataStr = line.substring(5).trim();
          
          if (dataStr === '[DONE]') {
            console.log('✅ 流式响应完成');
            continue;
          }

          try {
            const data = JSON.parse(dataStr);
            
            if (data.choices && data.choices.length > 0) {
              const delta = data.choices[0].delta;
              
              if (delta && delta.content) {
                aiMessage.content += delta.content;
                scrollToBottom();
              }
            }
          } catch (e) {
            console.warn('解析数据失败:', dataStr);
          }
        }
      }
    }

    // 如果窗口未打开，增加未读计数
    if (!showChat.value) {
      unreadCount.value++;
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送失败，请重试');
    
    // 移除失败的AI消息
    if (messages.value[messages.value.length - 1].role === 'assistant' && 
        !messages.value[messages.value.length - 1].content) {
      messages.value.pop();
    }
  } finally {
    isLoading.value = false;
    scrollToBottom();
  }
};

// 窗口大小改变时调整位置
const handleResize = () => {
  iconPosition.value = {
    x: Math.min(iconPosition.value.x, window.innerWidth - 60),
    y: Math.min(iconPosition.value.y, window.innerHeight - 60)
  };
  
  chatWindowPosition.value = {
    x: Math.min(chatWindowPosition.value.x, window.innerWidth - 360),
    y: Math.min(chatWindowPosition.value.y, window.innerHeight - 500)
  };
};

// 生命周期
onMounted(() => {
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', endDrag);
  window.addEventListener('resize', handleResize);
  
  console.log('✅ AI悬浮聊天组件已加载');
});

onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', endDrag);
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="less">
// 悬浮图标
.ai-floating-icon {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  cursor: move;
  z-index: 9998;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s, box-shadow 0.2s;
  user-select: none;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(102, 126, 234, 0.6);

    .icon-tooltip {
      opacity: 1;
      visibility: visible;
    }
  }

  &:active {
    transform: scale(0.95);
  }

  .icon-wrapper {
    position: relative;

    .ai-icon {
      color: white;
      animation: pulse 2s ease-in-out infinite;
    }

    .unread-badge {
      position: absolute;
      top: -5px;
      right: -5px;
      background: #f56c6c;
      color: white;
      font-size: 12px;
      padding: 2px 6px;
      border-radius: 10px;
      min-width: 18px;
      text-align: center;
      font-weight: bold;
    }
  }

  .icon-tooltip {
    position: absolute;
    left: -80px;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.2s, visibility 0.2s;
    pointer-events: none;

    &::after {
      content: '';
      position: absolute;
      right: -5px;
      top: 50%;
      transform: translateY(-50%);
      border: 5px solid transparent;
      border-left-color: rgba(0, 0, 0, 0.8);
    }
  }
}

// 聊天窗口
.ai-chat-window {
  position: fixed;
  width: 360px;
  height: 500px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .chat-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 12px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: move;
    user-select: none;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;

      .header-title {
        font-size: 14px;
        font-weight: 600;
      }
    }

    .header-actions {
      display: flex;
      gap: 4px;

      .header-btn {
        padding: 4px;
        min-height: auto;

        &:hover {
          background: rgba(255, 255, 255, 0.2);
        }
      }
    }
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    background: #f5f7fa;

    .welcome-message {
      text-align: center;
      padding: 40px 20px;
      color: #909399;

      p {
        margin: 10px 0 0;
        font-size: 14px;

        &:first-of-type {
          font-size: 16px;
          color: #303133;
          font-weight: 500;
        }
      }
    }

    .message-item {
      display: flex;
      margin-bottom: 16px;
      animation: messageSlide 0.3s ease;

      &.user {
        flex-direction: row-reverse;

        .message-content {
          align-items: flex-end;

          .message-text {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
          }
        }
      }

      &.assistant {
        .message-text {
          background: white;
          color: #303133;
        }
      }

      .message-avatar {
        flex-shrink: 0;
        margin: 0 8px;
      }

      .message-content {
        display: flex;
        flex-direction: column;
        max-width: 70%;

        .message-text {
          padding: 10px 14px;
          border-radius: 12px;
          line-height: 1.5;
          font-size: 13px;
          word-break: break-word;
          white-space: pre-wrap;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
        }

        .message-time {
          margin-top: 4px;
          font-size: 11px;
          color: #909399;
          padding: 0 4px;
        }

        .typing-indicator {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 10px 14px;
          background: white;
          border-radius: 12px;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);

          span {
            width: 6px;
            height: 6px;
            background: #409EFF;
            border-radius: 50%;
            animation: typing 1.4s infinite;

            &:nth-child(2) {
              animation-delay: 0.2s;
            }

            &:nth-child(3) {
              animation-delay: 0.4s;
            }
          }
        }
      }
    }
  }

  .chat-input {
    padding: 12px;
    background: white;
    border-top: 1px solid #e4e7ed;

    :deep(.el-input__wrapper) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;
      border-radius: 8px;
    }
  }
}

// 动画
@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.7;
  }
  30% {
    transform: translateY(-8px);
    opacity: 1;
  }
}

@keyframes messageSlide {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 聊天窗口过渡动画
.chat-slide-enter-active,
.chat-slide-leave-active {
  transition: all 0.3s ease;
}

.chat-slide-enter-from {
  opacity: 0;
  transform: scale(0.9) translateY(20px);
}

.chat-slide-leave-to {
  opacity: 0;
  transform: scale(0.9) translateY(20px);
}

// 滚动条样式
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;

  &:hover {
    background: #c0c4cc;
  }
}
</style>

